package logic

import (
	"context"
	"errors"
	"github.com/google/uuid"
	"mooc_srv/models"
	"mooc_srv/pkg"
	"strconv"

	"mooc_srv/internal/svc"
	"mooc_srv/mooc"

	"github.com/zeromicro/go-zero/core/logx"
)

type OrderAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewOrderAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *OrderAddLogic {
	return &OrderAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 订单添加
func (l *OrderAddLogic) OrderAdd(in *mooc.OrderAddRequest) (*mooc.OrderAddResponse, error) {
	// todo: add your logic here and delete this line

	var err error

	//查询用户是否存在
	var u models.User
	u.ID = uint(in.UserId)
	err = u.GetUserInfo(int(in.UserId))
	if err != nil {
		logx.Error("用户查询失败")
		return nil, errors.New("用户查询失败")
	}

	if u.ID == 0 {
		logx.Error("用户不存在")
		return nil, errors.New("用户不存在")
	}

	//查询商品是否存在
	var g models.Goods
	g.ID = uint(in.GoodsId)
	err = g.GetGoodsInfo()
	if err != nil {
		logx.Error("商品查询失败")
		return nil, errors.New("商品查询失败")
	}

	if g.ID == 0 {
		logx.Error("商品不存在")
		return nil, errors.New("商品不存在")
	}

	//订单创建
	var o models.Order
	orderSn := uuid.NewString()
	total := g.GoodsPrice * float64(in.Num)
	o = models.Order{
		UserId:     int(in.UserId),
		GoodsId:    int(in.GoodsId),
		OrderSn:    orderSn,
		OrderTotal: total,
	}
	err = o.Create()
	if err != nil {
		logx.Error("订单创建失败")
		return nil, errors.New("订单创建失败")
	}

	//生成支付链接
	payUrl := pkg.Alipay(orderSn, strconv.Itoa(int(total)))

	return &mooc.OrderAddResponse{
		PayUrl: payUrl,
	}, nil
}
